package org.sith.taskrunner.servlets;

import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.TasksManager;
import org.sith.taskrunner.ejb.services.UserManagerService;

import javax.ejb.EJB;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

public class TaskListServlet extends HttpServlet {

	@EJB(name="UserManagerServiceEJB")
    UserManagerService userManagerService;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out;
		String acceptEncoding = request.getHeader("accept-encoding");
		if((acceptEncoding!=null)&&(acceptEncoding.indexOf("gzip")!=-1)){
			out = new PrintWriter(new GZIPOutputStream(response.getOutputStream()), false);
			response.setHeader("content-encoding", "gzip");
		}else{
			out = response.getWriter();
		}
		HttpSession session = request.getSession();
		ServletContext context = session.getServletContext();
		String contextPath = context.getContextPath();
		try{
				out.println("<html>");
				out.println("<head>");
				out.println("<title>Tasks List</title>");
				out.println("<meta name=\"Keywords\" content=\"tasks\">");
				out.println("</head>");
				out.println("<body bgcolor=#aabbff>");
				out.println("<div align=right>");
				out.println("<a>All registered users: "+ userManagerService.getUsersCount()+"</a><p>");
				out.println("<a>Current user: "+((User)session.getAttribute("user")).getLogin()+"</a>");
				out.println("<form name=form1 action=\"logout\">");
				out.println("<input type=\"submit\" value=\"LogOut\">");
				out.println("</form>");
				out.println("</div>");
				TasksManager tasksManager = (TasksManager)context.getAttribute("TasksManager");
				printAllTasks(tasksManager, out, contextPath);	
				out.println("<p><a href=\""+contextPath+"/core/experiments\">Experiments</a>");
				out.println("</body>");
				out.println("</html>");
		}finally{
			out.close();
		}
	}
	
	public void printAllTasks(TasksManager tasksManager, PrintWriter out, String contextPath){
		for(Map.Entry<String, String> entry : tasksManager.entrySet()){
			out.println("<p><a href=\""+contextPath+entry.getValue()+"\">"+entry.getKey()+"Task</a>");
		}	
	}

	public void init(ServletConfig config) {
	}

	public void destroy() {
	}
	

}
